/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.convertmsrunner.convertmsprocessbuilder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 *
 * @author Kenneth
 */
public class ConvertMSProcessBuilder {

    /**
     * the msConvertProcess that will be run
     */
    Process msConvertProcess;
    /**
     * the processBuilder that will set the installationdirectory as the
     * workingdirectory
     */
    ProcessBuilder msConvertProcessBuilder;
    /**
     * Propertyfile to tell this class where the .exe is located
     */
    Properties config = new Properties();
    /**
     * anything other than zero = resulted in an error
     */
    private int systemExitValue;
    /**
     * standard logger...
     */
    private static final Logger logger = Logger.getLogger(ConvertMSProcessBuilder.class);

    public int runProcess(File installationFolder, File rawFile, File outputFolder) throws IOException {
        try {
            List<String> command = new ArrayList<String>();
            command.add("msconvert ");
            command.add(rawFile.getAbsolutePath());
            command.add(" -o ");
            command.add(outputFolder.getAbsolutePath());
            for (String aCommand : command) {
                System.out.print(aCommand);
            }
            msConvertProcessBuilder = new ProcessBuilder(command);
            msConvertProcessBuilder.directory(installationFolder);
            msConvertProcess = msConvertProcessBuilder.start();
            StreamGobbler errorGobbler = new StreamGobbler(msConvertProcess.getErrorStream());
            StreamGobbler outputGobbler = new StreamGobbler(msConvertProcess.getInputStream());
            errorGobbler.start();
            outputGobbler.start();
            msConvertProcess.waitFor();
            try {
                systemExitValue = msConvertProcess.waitFor();
            } catch (Throwable ex1) {
                ex1.printStackTrace();
                return 1;
            }
        } finally {
            return systemExitValue;
        }
    }
}
